"""
Function Calling注册器
管理所有可调用的工具函数
"""

import asyncio
import inspect
import logging
from typing import Dict, Any, Callable, Optional

logger = logging.getLogger(__name__)


class FunctionRegistry:
    """函数注册器"""
    
    _registry: Dict[str, Dict[str, Any]] = {}
    
    @classmethod
    def register_function(cls, name: str, description: str = ""):
        """注册函数装饰器"""
        def decorator(func: Callable):
            cls._registry[name] = {
                'func': func,
                'description': description,
                'is_async': inspect.iscoroutinefunction(func)
            }
            logger.info(f"注册函数: {name} - {description}")
            return func
        return decorator
    
    @classmethod
    def get_function(cls, name: str) -> Optional[Callable]:
        """获取函数"""
        return cls._registry.get(name, {}).get('func')
    
    @classmethod
    def get_description(cls, name: str) -> str:
        """获取函数描述"""
        return cls._registry.get(name, {}).get('description', '')
    
    @classmethod
    def is_async(cls, name: str) -> bool:
        """检查函数是否为异步函数"""
        return cls._registry.get(name, {}).get('is_async', False)
    
    @classmethod
    async def call(cls, name: str, *args, **kwargs) -> Any:
        """调用函数"""
        entry = cls._registry.get(name)
        if not entry:
            raise ValueError(f'未注册的函数: {name}')
        
        func = entry['func']
        try:
            if entry['is_async']:
                result = await func(*args, **kwargs)
            else:
                loop = asyncio.get_event_loop()
                result = await loop.run_in_executor(None, lambda: func(*args, **kwargs))
            
            logger.info(f"函数调用成功: {name}")
            return result
            
        except Exception as e:
            logger.error(f"函数调用失败: {name} - {e}")
            raise
    
    @classmethod
    def list_functions(cls) -> Dict[str, str]:
        """列出所有注册的函数"""
        return {name: entry['description'] for name, entry in cls._registry.items()}
    
    @classmethod
    def is_registered(cls, name: str) -> bool:
        """检查函数是否已注册"""
        return name in cls._registry
    
    @classmethod
    def unregister(cls, name: str) -> bool:
        """注销函数"""
        if name in cls._registry:
            del cls._registry[name]
            logger.info(f"注销函数: {name}")
            return True
        return False
    
    @classmethod
    def clear_registry(cls):
        """清空注册表"""
        cls._registry.clear()
        logger.info("清空函数注册表")
